<template>
  <div class="params_container">
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>分类参数</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区域 -->
    <el-card>
      <!-- 注意事项 -->
      <el-alert title="注意：只允许绘制三级分类设置参数" show-icon type="warning"></el-alert>
      <!-- 商品分类选择 -->
      <el-row class="cat_options">
        <el-col>
          <span>请选择商品分类：</span>
          <el-cascader
            v-model="cascaderVal"
            :options="cateList"
            expandTrigger="hover"
            :props="props"
            @change="handleCascaderChange"
            :closable="false"
          ></el-cascader>
        </el-col>
      </el-row>
      <!-- tabs选择 -->
      <el-tabs v-model="tabsVal" @tab-click="handleTabClick">
        <el-tab-pane label="动态参数" name="many">
          <el-button type="primary" :disabled="isBtnDisable" @click="dialogFormVisible = true">添加参数</el-button>
          <el-table :data="manyTabData" style="width: 100%;" border stripe>
            <el-table-column type="expand">
              <template slot-scope="props">
                <el-tag
                  v-for="(item,index) in props.row.attr_vals"
                  closable
                  @close="removeAttrName(props.row,index)"
                  :key="index"
                >{{item}}</el-tag>
                <el-input
                  class="input-new-tag"
                  v-if="props.row.inputVisible"
                  v-model="props.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(props.row)"
                  @blur="handleInputConfirm(props.row)"
                ></el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(props.row)"
                >+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index" width="50" label="序号"></el-table-column>
            <el-table-column prop="attr_name" label="参数名称"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-tooltip
                  class="item"
                  effect="dark"
                  content="编辑"
                  placement="top"
                  :enterable="false"
                >
                  <el-button
                    type="primary"
                    size="mini"
                    icon="el-icon-edit"
                    @click="showEditDialog(scope.row)"
                  ></el-button>
                </el-tooltip>
                <el-tooltip
                  class="item"
                  effect="dark"
                  content="删除"
                  placement="top"
                  :enterable="false"
                >
                  <el-button
                    type="danger"
                    size="mini"
                    icon="el-icon-delete"
                    @click="deleteParams(scope.row)"
                  ></el-button>
                </el-tooltip>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="静态属性" name="only">
          <el-button type="primary" :disabled="isBtnDisable" @click="dialogFormVisible=true">添加属性</el-button>
          <el-table :data="onlyTabData" style="width: 100%;" border stripe>
            <el-table-column type="expand">
              <template slot-scope="props">
                <el-tag
                  v-for="(item, index) in props.row.attr_vals"
                  closable
                  @close="removeParams(props.row)"
                  :key="index"
                >{{item}}</el-tag>
                <el-input
                  class="input-new-tag"
                  v-if="props.row.inputVisible"
                  v-model="props.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(props.row)"
                  @blur="handleInputConfirm(props.row)"
                ></el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(props.row)"
                >+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index" width="50" label="序号"></el-table-column>
            <el-table-column prop="attr_name" label="属性名称"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-tooltip
                  class="item"
                  effect="dark"
                  content="编辑"
                  placement="top"
                  :enterable="false"
                >
                  <el-button
                    type="primary"
                    size="mini"
                    icon="el-icon-edit"
                    @click="showEditDialog(scope.row)"
                  ></el-button>
                </el-tooltip>
                <el-tooltip
                  class="item"
                  effect="dark"
                  content="删除"
                  placement="top"
                  :enterable="false"
                >
                  <el-button
                    type="danger"
                    size="mini"
                    icon="el-icon-delete"
                    @click="deleteParams(scope.row)"
                  ></el-button>
                </el-tooltip>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <!-- 添加参数的对话框 -->
    <el-dialog
      :title="'添加'+titleText"
      :visible.sync="dialogFormVisible"
      width="40%"
      :show-close="false"
      :modal="true"
      :close-on-click-modal="false"
    >
      <el-form :model="addForm" :rules="rules" ref="addFormRef">
        <el-form-item :label="titleText" label-width="20%" prop="attr_name">
          <el-input v-model="addForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible=false">取 消</el-button>
        <el-button type="primary" @click="admit">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 修改参数的对话框 -->
    <el-dialog
      :title="'更改'+titleText"
      :visible.sync="editDialogVisible"
      width="40%"
      :show-close="false"
      :modal="true"
      :close-on-click-modal="false"
    >
      <el-form :model="editForm" :rules="rules" ref="editFormRef">
        <el-form-item :label="titleText" label-width="20%" prop="attr_name">
          <el-input v-model="editForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible=false">取 消</el-button>
        <el-button type="primary" @click="submitEditForm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 级联选择器全部显示数据
      cateList: [],
      // 级联选择器选中数据
      cascaderVal: [],
      // 级联选择器选项
      props: {
        label: 'cat_name',
        value: 'cat_id',
        children: 'children'
      },
      // tabs的参数
      tabsVal: 'many',
      // 动态参数的数据
      manyTabData: [],
      // 静态参数的数据
      onlyTabData: [],
      dialogFormVisible: false,
      rules: {
        attr_name: {
          required: true,
          message: '请输入至少一个字符',
          trigger: 'blur'
        }
      },
      addForm: {
        attr_name: ''
      },
      // 编辑框显示
      editDialogVisible: false,
      // 修改的表单数据对象
      editForm: {
        attr_name: ''
      },
      // 添加参数表单显示
      inputVisible: false,
      // 添加参数表单值
      inputValue: ''
    }
  },
  created() {
    this.getCateList()
  },
  methods: {
    // 获取级联选择器数据信息
    async getCateList() {
      const { data: res } = await this.$http.get('categories')
      if (res.meta.status != 200) {
        return this.$message.error('获取数据失败')
      }
      this.cateList = res.data
      // console.log(this.cateList)
    },
    // 监听级联选择器改变
    async handleCascaderChange() {
      if (!this.cascaderVal[2]) {
        return
      }
      const { data: res } = await this.$http.get(
        `categories/${this.cateId}/attributes`,
        {
          params: { sel: this.tabsVal }
        }
      )
      if (res.meta.status != 200) {
        return this.$message.error('获取数据失败')
      }
      res.data.forEach(item => {
        item.attr_vals = item.attr_vals.split(' ')
        item.inputVisible = false
        item.inputValue = ''
      })
      if (this.tabsVal == 'only') {
        console.log(this.onlyTabData, 'onlydata')
        return (this.onlyTabData = res.data)
      }
      this.manyTabData = res.data
      console.log(this.manyTabData)
    },
    // 监听分类参数变化，发起数据请求。tabs的点击,自带的方法默认传两个参数
    handleTabClick(tab, event) {
      // console.log(tab, event)
      console.log(this.tabsVal)
      this.handleCascaderChange()
    },
    // 添加的参数传值，点击添加的dialog确定
    admit() {
      console.log(this.addForm.attr_name, this.cateId, this.tabsVal)
      this.$refs.addFormRef.validate(valid => {
        if (!valid) {
          this.$message.closeAll()
          return this.$message.error('请检查表单信息')
        }
        this.$http
          .post(`categories/${this.cateId}/attributes`, {
            attr_name: this.addForm.attr_name,
            attr_sel: this.tabsVal
          })
          .then(res => {
            // console.log(res)
            if (res.data.meta.status != 201) {
              this.$message.closeAll()
              return this.$message.error('添加失败')
            }
            this.$message.success('添加成功')
            this.$router.go(0)
          })
      })
    },
    // 显示窗口
    async showEditDialog(data) {
      this.editDialogVisible = true
      const { data: res } = await this.$http.get(
        `categories/${this.cateId}/attributes/${data.attr_id}`,
        {
          params: {
            attr_sel: this.tabsVal
          }
        }
      )
      if (res.meta.status != 200) {
        return this.$message.error('获取数据失败')
      }
      this.editForm = res.data
    },
    // 修改参数对话框提交
    submitEditForm() {
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) {
          this.$message.closeAll()
          return this.$message.error('请检查表单信息')
        }
        const { data: res } = await this.$http.get(
          `categories/${this.cateId}/attributes/${this.editForm.attr_id}`,
          {
            params: {
              attr_name: this.editForm.attr_name,
              attr_sel: this.editForm.attr_sel
            }
          }
        )
        if (res.meta.status != 200) {
          return this.$message.error('修改失败')
        }
        console.log(res)
      })
    },
    // 删除参数提交
    deleteParams(data) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          // console.log(data)
          const { data: res } = await this.$http.delete(
            `categories/${this.cateId}/attributes/${data.attr_id}`
          )
          if (res.meta.status != 200) {
            return this.$message.error('删除失败')
          }
          this.$message.success('删除成功')
          this.$router.go(0)
        })
        .catch(() => {
          console.log('取消删除')
        })
    },

    // 删除属性、参数的某个attr_vals
    async removeAttrName(data, index) {
      data.attr_vals.splice(index, 1)
      console.log(data.attr_vals, index)
      const res = await this.saveAttrValves(data)
      if (res.data.meta.status != 200) {
        return this.$message.error('删除失败')
      }
      return this.$message.success('删除成功！')
    },

    //显示添加params的input框
    showInput() {
      this.inputVisible = true
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    // 编辑操作提交
    async handleInputConfirm(data) {
      console.log(data)
      // 对输入的数据进行检验
      if (data.inputValue.trim().length === 0) {
        data.inputVisible = false
        data.inputValue = ''
        return this.$message.error('输入不能为空')
      }
      // 检验成功后提交
      data.attr_vals.push(data.inputValue.trim())
      data.inputVisible = false
      data.inputValue = ''
      const res = await this.saveAttrValves(data)
      console.log(res)
      if (res.data.meta.status != 200) {
        return this.$message.error('添加失败')
      }
      return this.$message.success('添加成功！')
    },
    // 输入框显示,并聚焦于input输入框
    showInput(data) {
      data.inputVisible = true
      this.$nextTick(_ => {
        this.$refs.saveTagInput.focus()
      })
    },
    // 将对attr_vals的操作发送到数据库
    saveAttrValves(data) {
      return this.$http.put(
        `categories/${this.cateId}/attributes/${data.attr_id}`,
        {
          attr_name: data.attr_name,
          attr_vals: data.attr_vals.join(' '),
          attr_sel: data.attr_sel
        }
      )
    }
  },

  // 计算属性
  computed: {
    // 按钮需要被禁用返回true，否则返回false
    isBtnDisable() {
      if (this.cascaderVal.length != 3) {
        return true
      }
      return false
    },
    // 当前选中的三级id
    cateId() {
      return this.cascaderVal[2]
    },
    // dialog标题
    titleText() {
      if (this.tabsVal == 'many') {
        return '动态参数'
      }
      return '静态属性'
    }
  }
}
</script>

<style lang="less" scoped>
.params_container {
  .el-card {
    margin-top: 20px;
    .cat_options {
      margin: 15px 10px;
    }
    .el-tab-pane > .el-button {
      margin-bottom: 15px;
    }
  }
  .el-tag {
    margin-right: 10px;
  }
  .el-table .el-input {
    width: 150px;
  }
}
</style>